import logging
import pymysql
from django.core.exceptions import ObjectDoesNotExist
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db import transaction
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser

from rest_framework.views import APIView

from backend.common.Base64JJM import Jiami, Jiemi
from backend.common.api_response import JsonResponse
from backend.datebase.searchDatebaseTableAndColumn import list_table

from backend.models import Lyzd_Datebase_Config, Lyzd_Table_Config

from backend.serializers import LyzdDBConfigSerializer, LyzdTableConfigSerializer

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。


class LyzdDBConfigList(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):

        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")

        name = request.GET.get("name")

        obi = Lyzd_Datebase_Config.objects.filter(name__contains=name).order_by("-id")

        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数

        try:

            obm = paginator.page(page)

        except PageNotAnInteger:

            obm = paginator.page(1)
        except EmptyPage:

            obm = paginator.page(paginator.num_pages)
        """
        用途前端处理，后端处理的话需要更新2个py文件才可以所以前端处理
        
        """

        serialize = LyzdDBConfigSerializer(obm, many=True)

        return JsonResponse(data={"data": serialize.data,
                                  "page": page,
                                  "total": total
                                  }, code="999999", msg="成功")


class AddDatabase(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()


    def parameter_check(self, data):

        """
        验证参数
        :param data:
        :return:
        """
        try:
            # 必传参数 name, version, type
            if not data["name"] or not data["port"] or not data["host"] or not data["user"] or not data["password"]:
                return JsonResponse(code="999996", msg="参数有误！")

        except KeyError:
            return JsonResponse(code="999996", msg="参数有误！")

    def post(self, request):
        """
        新增模块
        :param request:
        :return:
        """
        data = JSONParser().parse(request)
        result = self.parameter_check(data)

        if result:
            return result
        data["create_user"] = request.user.pk
        ptoject_serializer = LyzdDBConfigSerializer(data=data)

        try:
            Lyzd_Datebase_Config.objects.get(name=data["name"])

            return JsonResponse(code="999997", msg="存在相同数据库配置名称")
        except ObjectDoesNotExist:
            with transaction.atomic():
                # a = Jiami(str1)

                db_data = Lyzd_Datebase_Config(

                    name=data["name"],
                    port=Jiami(data["port"]),
                    host=Jiami(data["host"]),
                    user=Jiami(data["user"]),
                    password=Jiami(data["password"]),
                    database=data["database"],

                )
                try:
                    db_data.save()

                    return JsonResponse(code="999999", msg="成功")
                except:
                    return JsonResponse(code="999997", msg="失败")


class AddTable(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def parameter_check(self, data):

        """
        验证参数
        :param data:
        :return:
        """
        try:
            # 必传参数 name, version, type
            if not data["name"] or not data["table_name"] or not data["database"] or not data["condition"]:
                return JsonResponse(code="999996", msg="参数有误！")



        except KeyError:
            return JsonResponse(code="999996", msg="参数有误！")

    def post(self, request):
        """
        新增模块
        :param request:
        :return:
        """
        data = JSONParser().parse(request)
        result = self.parameter_check(data)

        if result:
            return result
        data["create_user"] = request.user.pk
        table_serializer = LyzdTableConfigSerializer(data=data)

        try:
            Lyzd_Table_Config.objects.get(name=data["name"])

            return JsonResponse(code="999997", msg="存在相同数据表配置名称")
        except ObjectDoesNotExist:
            with transaction.atomic():

                # a = Jiami(str1)
                conditionValue = ''
                try:
                    conditionValue = data["conditionValue"]
                except:

                    conditionValue = ''

                try:
                    content = data["content"]
                except:
                    content = ''

                if conditionValue != '':
                    # print(1)
                    # print(conditionValue)
                    # print(type(conditionValue))
                    count2 = conditionValue.count(',')
                    # print(count2)
                    condition = data["condition"]
                    if count2 != condition.count(','):
                        return JsonResponse(code="999997", msg="条件与条件值数量不匹配")
                db_data = Lyzd_Table_Config(
                    name=data["name"],
                    database=data["database"],
                    table_name=data["table_name"],
                    condition=data["condition"],
                    conditionValue=conditionValue,
                    content=content,
                )
                try:
                    db_data.save()
                    return JsonResponse(code="999999", msg="成功")
                except:
                    return JsonResponse(code="999997", msg="失败")


class LyzdTableConfigList(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))
        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")
        name = request.GET.get("name")
        obi = Lyzd_Table_Config.objects.filter(name__contains=name).order_by("-id")
        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数
        try:
            obm = paginator.page(page)
        except PageNotAnInteger:
            obm = paginator.page(1)
        except EmptyPage:
            obm = paginator.page(paginator.num_pages)
        """
        用途前端处理，后端处理的话需要更新2个py文件才可以所以前端处理

        """
        serialize = LyzdTableConfigSerializer(obm, many=True)
        return JsonResponse(data={"data": serialize.data,
                                  "page": page,
                                  "total": total
                                  }, code="999999", msg="成功")


class LyzdTableBackUpGetTables(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):

        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")

        id = request.GET.get("db_id")

        obi = Lyzd_Datebase_Config.objects.filter(id=id)

        db = obi[0]

        host = Jiemi(db.host)
        user = Jiemi(db.user)
        port = Jiemi(db.port)
        password = Jiemi(db.password)
        database = db.databaseName

        tables = list_table(host, user, password, database)

        return JsonResponse(data={"database": database,
                                  "data": tables,
                                  "page": page, }, code="999999")
